<?php

namespace App\Supports\Payment\Channels;

use Exception;
use Monolog\Logger;
use Yansongda\Pay\Pay;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use App\Supports\Payment\Contracts\Channel;
use App\Supports\Payment\Contracts\PayChannel;
use Rainsens\Dinglog\Facades\Dinglog;

class AliPay extends Channel implements PayChannel
{
	public function __construct()
	{
		$this->channelName = 'alipay';
		$this->setConfig();
		$this->setOrigin();
	}

	public function setConfig()
	{
		$route = cs()->alipay_route;

		$action = $this->getRouteAction();

		if($action == "withdrawStore" || $action =="alipayPayload" || $action =="alipayBind"){

			$this->config = config("alipay.YJLS");
		}else{
			$this->config = config("alipay.ZSJD");
		}
	}

	public function setOrigin()
	{
		$config = $this->config;
		$config['notify_url'] = route('web.payments.alipay.notify');

		if (app()->environment('production')) {
			$config['log']['level'] = Logger::WARNING;
		} else {
			$config['log']['level'] = Logger::DEBUG;
		}
		$this->origin = Pay::alipay($config);
	}

	public function tools($data = null)
	{
		// TODO: Implement tools() method.
	}

	public function getChannelName()
	{
		return $this->channelName;
	}

	public function getRouteAction()
	{
		$routeAction = explode('@', Route::currentRouteAction());
		$action = $routeAction[1];
		return $action;
	}

	public function verify($data = null)
	{
		return $this->origin->verify();
	}

	public function find($data = null)
	{
		// TODO: Implement find() method.
	}

	public function pay($data = null)
	{
		try {
			$action = $this->getRouteAction();
			if ($action == 'payOrderByAliwap'
				or $action == 'payVipPurchaseByAliwap'
				or $action == 'payGoldChargeByAliwap') {
				 $returnUrl = app()->environment('production')
					? 'https://shopwap.littleshop.shop/#/packs/pages/order/paid'
					: 'https://shopwapdev.littleshop.shop/#/packs/pages/order/paid';
				$data['return_url'] = $returnUrl;
				$response = $this->origin->wap($data);
			} else {
				$response = $this->origin->app($data);
			}
			return $response->getContent();
		} catch (Exception $exception) {
			$message = $exception->getCode().$exception->getMessage();
			throw new Exception($message);
		}
	}

	public function refund($data = null)
	{
		try {
			return $this->origin->refund($data);
		} catch (Exception $exception) {
			$message = $exception->getCode().$exception->getMessage();
			throw new Exception($message);
		}
	}

	public function transfer($data = null)
	{
		try {

				Dinglog::text(json_encode($this->config));
			return $this->origin->transfer($data);
		} catch (Exception $exception) {
			$message = $exception->getCode().$exception->getMessage();
			throw new Exception($message);
		}
	}

	public function query($data = null)
	{
		// TODO: Implement query() method.
	}
}
